import React, { useRef } from 'react';
import { Input, Popover } from 'antd';
import { SketchPicker } from 'react-color';
import './styles.less';

export interface IColorInputProps {
  value?: string;
  onChange?: (color: string) => void;
  onBlur?: () => void;
  placement?:
  | 'top'
  | 'left'
  | 'right'
  | 'bottom'
  | 'topLeft'
  | 'topRight'
  | 'bottomLeft'
  | 'bottomRight'
  | 'leftTop'
  | 'leftBottom'
  | 'rightTop'
  | 'rightBottom';
  isGetPopupContainer?: boolean; // 是否渲染到body上
  defualtFocuse?: boolean;
  isPicker?: boolean
}

const ColorInput: React.FC<IColorInputProps> = (props) => {
  const container = useRef<any>();
  const prefix = 'dn-color-input';
  const color = props.value as string;
  const openRef = useRef(false);
  return (
    <div
      ref={container}
      className={prefix}
    >
      <Input
        autoFocus={props.defualtFocuse ? true : false}
        onBlur={
          props.defualtFocuse
            ? () => {
              setTimeout(() => {
                if (openRef.current === false) {
                  props.onBlur?.();
                }
              }, 200);
            }
            : undefined
        }
        value={props.value}
        onChange={(e) => {
          props.onChange?.(e.target.value);
        }}
        placeholder="Color"
        prefix={
          props?.isPicker === false ?
            <div
              className={prefix + '-color-tips'}
              style={{
                backgroundColor: color,
              }}
            /> :
            <Popover
              overlayClassName='color-input-popover'
              onVisibleChange={
                props.defualtFocuse
                  ? (visible) => {
                    openRef.current = visible;
                    if (!visible) {
                      props.onBlur?.();
                    }
                  }
                  : undefined
              }
              autoAdjustOverflow
              trigger='click'
              placement={props.placement || 'top'}
              overlayInnerStyle={{ padding: 0 }}
              getPopupContainer={
                props.isGetPopupContainer
                  ? undefined
                  : () => container.current as HTMLDivElement
              }
              content={
                <SketchPicker
                  color={color}
                  onChange={({ rgb }) => {
                    props.onChange?.(`rgba(${rgb.r},${rgb.g},${rgb.b},${rgb.a})`);
                  }}
                />
              }
            >
              <div
                className={prefix + '-color-tips'}
                style={{
                  backgroundColor: color,
                }}
              />
            </Popover>
        }
      />
    </div>
  );
};

export default ColorInput;